package net.oschina.foodon.examples.spring.cloud.service.consumer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * Created by foodon on 2017/4/9.
 */
@RestController
public class ConsumerRestController {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private DiscoveryClient discoveryClient;

    /**
     * 调用远端服务输出
     *
     * @return result 结算结果
     */
    @RequestMapping(value = "/ui", method = RequestMethod.GET)
    public String add() {
        String result = restTemplate.getForEntity("http://spring-cloud-service-provider/add?a=10&b=20", String.class).getBody();

        return "结果是：" + result;
    }

    /**
     * 从所有服务中选择一个服务（轮询）
     */
    @RequestMapping("/discover")
    public Object discover() {
        return loadBalancerClient.choose("spring-cloud-service-provider").getUri().toString();
    }

    /**
     * 获取所有服务
     */
    @RequestMapping("/services")
    public Object services() {
        return discoveryClient.getInstances("spring-cloud-service-provider");
    }
}
